<template>
  <el-dialog :title="title"
             :visible.sync="dialogVisible"
             width="531px">
    <el-form
        ref="form"
        :model="form"
        label-width="100px"
        label-suffix="："
    >
      <el-form-item label="充值条数" :rules="[{required: true, message:'请输入充值条数'}]" prop="count">
        <el-input v-model="form.count"
                  size="small"
                  placeholder="请输入充值条数"></el-input>
      </el-form-item>
      <el-form-item label="单价" :rules="[{required: true, message:'请输入单价'}]" prop="price">
        <el-input v-model="form.price"
                  size="small"
                  placeholder="请输入单价"></el-input>
      </el-form-item>
      <el-form-item label="充值金额" :rules="[{required: true, message:'请输入充值金额'}]" prop="money">
        <el-input v-model="form.money"
                  size="small"
                  placeholder="请输入充值金额"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
          size="small"
          @click="dialogVisible = false"
      >
        取 消
      </el-button>
      <el-button
          size="small"
          type="primary"
          :loading="submit_loading"
          @click="ensure"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "editTemplate",
  data() {
    return {
      dialogVisible: false,
      form: {
        id: '',
        count: '',
        price: '',
        money: ''
      },
      isNew: true,
      submit_loading: false
    }
  },
  computed: {
    title() {
      const isNew = this.isNew
      return isNew ? '新增模板' : '编辑模板'
    }
  },
  methods: {
    open(row) {
      this.isNew = row === undefined
      row = row || {}
      let form = {}
      Object.keys(this.form).forEach(key => {
        form[key] = row[key] || ''
      })
      this.form = form
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    ensure() {
      this.$refs.form.validate(async valid => {
        if (!valid) return false
        const isNew = this.isNew
        const url = isNew ? '/api/v1/sms/recharge/template/save' : '/api/v1/sms/recharge/template/update'
        this.submit_loading = true
        const params = {}
        Object.keys(this.form).forEach(key => {
          if (key === 'id') {
            params[key] = this.form[key]
          } else {
            params[key] = parseFloat(this.form[key])
          }
        })
        if (!isNew) {
          params.state = 1
        }
        await this.$axios.post(url, params).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.$emit('success')
          }
        }).catch(err => {
          this.$message.error(err.message)
        })
        this.submit_loading = false
      })
    }
  }
}
</script>

<style scoped>

</style>